import { Modal, Form, message } from 'antd';
import ProForm, { ProFormText, ProFormDigit } from '@ant-design/pro-form';
import { save, update } from '@/services/system/job';
import {SystemDeptTreeSelect} from '@/components/system/dept'
import {SystemDutyTreeSelect} from '@/components/system/duty'

const SystemJobForm = (props) => {

  const [form] = Form.useForm();
  const { formVisible, onSubmit, onCancel, values } = props;

  const saveHandle = async (formValue) => {
    const data = await save(formValue);

    if (data.success) message.success('新建岗位成功!');
    else message.error('新建岗位失败!');
  };

  const updateHandle = async (formValue) => {
    const data = await update(formValue);

    if (data.success) message.success('修改岗位成功!');
    else message.error('修改岗位失败!');
  };

  const okHandle = async () => {
    const fieldsValue = await form.validateFields();
    const formValue = { ...values, ...fieldsValue };

    if (formValue.id) await updateHandle(formValue);
    else await saveHandle(formValue);

    onSubmit();
  }

  return (
    <Modal
      destroyOnClose
      title={values.id ? '修改岗位信息' : '新增岗位信息'}
      visible={formVisible}
      onOk={okHandle}
      onCancel={onCancel}
    >
      <ProForm 
        initialValues={values} 
        form={form} submitter={false}
        layout={'horizontal'} labelCol= { {span: 4} } wrapperCol= { {span: 20} }
      >
        <Form.Item label="所属机构" name="deptId" rules={[{ required: true, message: '请选择所属机构!' }]}>
          <SystemDeptTreeSelect />
        </Form.Item>
        <Form.Item label="所属职务" name="dutyId" rules={[{ required: true, message: '请选择所属职务!' }]}>
          <SystemDutyTreeSelect />
        </Form.Item>
        <ProFormText  name="name" label="岗位名称" rules={[{ required: true, message: '请输入岗位名称!' }, {max: 50, message: '岗位名称过长!'}]} />
        <ProFormText  name="code" label="岗位编码" rules={[{ required: true, message: '请输入岗位编码!' }, {max: 200, message: '岗位编码过长!'}]}/>
        <ProFormDigit name="sort" label="岗位排序" min={1} max={10000} defaultValue={1} rules={[{ required: true, message: '请输入岗位排序!' }]}/>
      </ProForm>
    </Modal>
  );
}

export default SystemJobForm;